<template>
  <PageLayout
    title="用户管理"
    subtitle="管理系统用户账户"
    icon="fa fa-user"
    class="apply-glass-theme"
  >
    <template #toolbar-left>
      <el-button v-permission="'write'" type="primary" @click="showCreateDialog" class="tech-button">
        <i class="fa fa-plus"></i> 新增用户
      </el-button>
      <el-button @click="refreshUsers" class="tech-button">
        <i class="fa fa-refresh"></i> 刷新
      </el-button>
    </template>

    <template #toolbar-right>
      <el-input
        v-model="searchText"
        placeholder="搜索用户名、邮箱或姓名..."
        clearable
        class="tech-input"
        style="width: 350px"
      >
        <template #prefix>
          <i class="fa fa-search"></i>
        </template>
      </el-input>
    </template>

    <template #content>
      <div class="glass-card">
        <el-table
          :data="filteredUsers"
          v-loading="loading"
          class="glass-dialog tech-table"
          stripe
          border
          height="calc(100vh - 380px)"
          style="width: 100%;"
          table-layout="fixed"
        >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="first_name" label="姓名" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'">
              {{ row.is_active ? '激活' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="角色" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.is_superuser" type="danger">超级管理员</el-tag>
            <el-tag v-else-if="row.is_staff" type="warning">管理员</el-tag>
            <el-tag v-else type="info">普通用户</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="date_joined" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.date_joined) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350" fixed="right" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                v-permission="'write'"
                size="small"
                type="primary"
                @click="editUser(row)"
                class="action-btn glass-button"
              >
                <i class="fa fa-edit"></i> 编辑
              </el-button>
              <el-button
                v-permission="'write'"
                size="small"
                type="warning"
                @click="changePassword(row)"
                class="action-btn glass-button"
              >
                <i class="fa fa-key"></i> 改密码
              </el-button>
              <el-button
                v-permission="'write'"
                size="small"
                type="danger"
                @click="deleteUser(row)"
                class="action-btn glass-button"
              >
                <i class="fa fa-trash"></i> 删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      </div>
    </template>

    <template #dialogs>
      <!-- 创建/编辑用户对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="650px"
        class="tech-dialog"
      >
        <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="100px" class="tech-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="userForm.username" :disabled="isEdit" placeholder="请输入用户名" class="tech-input" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="userForm.email" type="email" placeholder="请输入邮箱地址" class="tech-input" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="姓名" prop="first_name">
                <el-input v-model="userForm.first_name" placeholder="请输入姓名" class="tech-input" />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="!isEdit">
              <el-form-item label="密码" prop="password">
                <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password class="tech-input" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20" v-if="!isEdit">
            <el-col :span="12">
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input v-model="userForm.confirmPassword" type="password" placeholder="请再次输入密码" show-password class="tech-input" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="用户组" prop="groups">
                <el-select
                  v-model="userForm.groups"
                  multiple
                  placeholder="请选择用户组（可多选）"
                  style="width: 100%"
                  filterable
                  class="tech-input"
                >
                  <el-option
                    v-for="group in userGroups"
                    :key="group.id"
                    :label="group.name"
                    :value="group.id"
                  >
                    <span>{{ group.name }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="状态">
                <el-switch v-model="userForm.is_active" active-text="激活" inactive-text="禁用" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="管理员">
                <el-switch v-model="userForm.is_staff" active-text="是" inactive-text="否" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="超级管理员">
                <el-switch v-model="userForm.is_superuser" active-text="是" inactive-text="否" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false" class="tech-button">取消</el-button>
            <el-button type="primary" @click="saveUser" class="tech-button">
              {{ isEdit ? '更新' : '创建' }}
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 修改密码对话框 -->
      <el-dialog
        v-model="passwordDialogVisible"
        title="修改用户密码"
        width="450px"
        class="tech-dialog"
      >
        <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px" class="tech-form">
          <el-form-item label="用户名">
            <el-input v-model="passwordForm.username" disabled class="tech-input" />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password class="tech-input" />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password class="tech-input" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="passwordDialogVisible = false" class="tech-button">取消</el-button>
            <el-button type="primary" @click="savePassword" class="tech-button">
              修改密码
            </el-button>
          </div>
        </template>
      </el-dialog>
    </template>
  </PageLayout>
</template>

<script setup lang="ts">
import PageLayout from '@/components/PageLayout.vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, ref } from 'vue'


// 响应式数据
const loading = ref(false)
const users = ref([])
const userGroups = ref([])
const searchText = ref('')
const dialogVisible = ref(false)
const passwordDialogVisible = ref(false)
const isEdit = ref(false)
const userFormRef = ref()
const passwordFormRef = ref()

// 用户表单
const userForm = ref({
  id: null,
  username: '',
  email: '',
  first_name: '',
  password: '',
  confirmPassword: '',
  is_active: true,
  is_staff: false,
  is_superuser: false,
  groups: []
})

// 密码表单
const passwordForm = ref({
  id: null,
  username: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  first_name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少 6 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value !== userForm.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 密码表单验证规则
const passwordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少 6 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑用户' : '新增用户')
const filteredUsers = computed(() => {
  if (!searchText.value) return users.value
  return users.value.filter((user: any) =>
    user.username.toLowerCase().includes(searchText.value.toLowerCase()) ||
    user.email.toLowerCase().includes(searchText.value.toLowerCase()) ||
    user.first_name.toLowerCase().includes(searchText.value.toLowerCase())
  )
})

// 方法
const fetchUsers = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/users/')
    users.value = response.data.results || response.data
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const fetchUserGroups = async () => {
  try {
    const response = await axios.get('/api/groups/')
    userGroups.value = response.data.results || response.data
  } catch (error) {
    console.error('获取用户组列表失败:', error)
    ElMessage.error('获取用户组列表失败')
  }
}

const refreshUsers = () => {
  fetchUsers()
}

const showCreateDialog = () => {
  isEdit.value = false
  userForm.value = {
    id: null,
    username: '',
    email: '',
    first_name: '',
    password: '',
    confirmPassword: '',
    is_active: true,
    is_staff: false,
    is_superuser: false,
    groups: []
  }
  dialogVisible.value = true
}

const editUser = (user: any) => {
  isEdit.value = true
  userForm.value = {
    id: user.id,
    username: user.username,
    email: user.email,
    first_name: user.first_name,
    password: '',
    confirmPassword: '',
    is_active: user.is_active,
    is_staff: user.is_staff,
    is_superuser: user.is_superuser,
    groups: user.groups ? user.groups.map((g: any) => g.id) : []
  }
  dialogVisible.value = true
}

const saveUser = async () => {
  try {
    await userFormRef.value.validate()

    const userData = { ...userForm.value }
    delete userData.confirmPassword

    if (isEdit.value) {
      delete userData.password
      await axios.put(`/api/users/${userData.id}/`, userData)
      ElMessage.success('用户更新成功')
    } else {
      await axios.post('/api/users/', userData)
      ElMessage.success('用户创建成功')
    }

    dialogVisible.value = false
    fetchUsers()
  } catch (error) {
    console.error('保存用户失败:', error)
    ElMessage.error('保存用户失败')
  }
}

const changePassword = (user: any) => {
  passwordForm.value = {
    id: user.id,
    username: user.username,
    newPassword: '',
    confirmPassword: ''
  }
  passwordDialogVisible.value = true
}

const savePassword = async () => {
  try {
    await passwordFormRef.value.validate()

    await axios.patch(`/api/users/${passwordForm.value.id}/admin-change-password/`, {
      password: passwordForm.value.newPassword
    })

    ElMessage.success('密码修改成功')
    passwordDialogVisible.value = false
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败')
  }
}

const deleteUser = async (user: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这个用户吗？', '确认删除', {
      type: 'warning'
    })

    await axios.delete(`/api/users/${user.id}/`)
    ElMessage.success('用户删除成功')
    fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  }
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  fetchUsers()
  fetchUserGroups()
})
</script>

<style scoped>
/* 透明玻璃按钮样式 */
:deep(.el-button) {
  background: rgba(255, 255, 255, 0.05) !important;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  backdrop-filter: blur(10px) !important;
  transition: all 0.3s ease !important;
  border-radius: 8px !important;
  font-weight: 500 !important;

  &:hover {
    background: rgba(255, 255, 255, 0.1) !important;
    border-color: rgba(0, 234, 255, 0.3) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2) !important;
    color: #ffffff !important;
  }

  &.el-button--primary {
    background: linear-gradient(135deg, rgba(0, 234, 255, 0.8), rgba(0, 153, 204, 0.8)) !important;
    border-color: rgba(0, 234, 255, 0.6) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 15px rgba(0, 234, 255, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, rgba(51, 240, 255, 0.9), rgba(0, 184, 230, 0.9)) !important;
      box-shadow: 0 6px 20px rgba(0, 234, 255, 0.4) !important;
      border-color: rgba(0, 234, 255, 0.8) !important;
    }
  }

  &.el-button--warning {
    background: linear-gradient(135deg, rgba(255, 193, 7, 0.8), rgba(255, 152, 0, 0.8)) !important;
    border-color: rgba(255, 193, 7, 0.6) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 15px rgba(255, 193, 7, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, rgba(255, 206, 84, 0.9), rgba(255, 167, 38, 0.9)) !important;
      box-shadow: 0 6px 20px rgba(255, 193, 7, 0.4) !important;
    }
  }

  &.el-button--danger {
    background: linear-gradient(135deg, rgba(220, 53, 69, 0.8), rgba(176, 42, 55, 0.8)) !important;
    border-color: rgba(220, 53, 69, 0.6) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 15px rgba(220, 53, 69, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, rgba(225, 83, 97, 0.9), rgba(190, 60, 75, 0.9)) !important;
      box-shadow: 0 6px 20px rgba(220, 53, 69, 0.4) !important;
    }
  }

  &.el-button--info {
    background: linear-gradient(135deg, rgba(108, 117, 125, 0.8), rgba(73, 80, 87, 0.8)) !important;
    border-color: rgba(108, 117, 125, 0.6) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 15px rgba(108, 117, 125, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, rgba(130, 138, 145, 0.9), rgba(90, 98, 104, 0.9)) !important;
      box-shadow: 0 6px 20px rgba(108, 117, 125, 0.4) !important;
    }
  }

  &:disabled {
    background: rgba(255, 255, 255, 0.02) !important;
    border-color: rgba(255, 255, 255, 0.05) !important;
    color: rgba(255, 255, 255, 0.3) !important;
    cursor: not-allowed !important;
    transform: none !important;
    box-shadow: none !important;
  }
}

/* 操作按钮容器样式优化 */
.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: nowrap;
  justify-content: center;
  align-items: center;
  min-width: 300px;
  padding: 4px;
}

.action-btn {
  min-width: 80px !important;
  height: 34px !important;
  padding: 0 12px !important;
  border-radius: 8px !important;
  font-size: 12px !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  transition: all 0.3s ease !important;
  white-space: nowrap !important;
  flex-shrink: 0 !important;

  i {
    font-size: 12px !important;
    margin-right: 4px !important;
  }
}

/* 确保表格操作列有足够的空间且不被遮挡 */
:deep(.el-table .el-table__cell) {
  padding: 8px 4px !important;
  position: relative !important;
}

:deep(.el-table .el-table__cell:has(.action-buttons)) {
  padding: 8px 12px !important;
  overflow: visible !important;
  z-index: 10 !important;
  position: relative !important;
}

/* 优化表格行高 */
:deep(.el-table .el-table__row) {
  height: 50px !important;
  position: relative !important;
}

/* 确保固定列不遮挡按钮 */
:deep(.el-table__fixed-right) {
  z-index: 5 !important;
}

:deep(.el-table__fixed-right .el-table__cell) {
  z-index: 10 !important;
  background: rgba(13, 21, 43, 0.95) !important;
  backdrop-filter: blur(10px) !important;
}

/* 确保按钮在小屏幕上也能正常显示 */
@media (max-width: 1200px) {
  .action-buttons {
    flex-wrap: wrap;
    gap: 4px;
    min-width: 260px;
  }

  .action-btn {
    min-width: 70px !important;
    font-size: 11px !important;
    padding: 0 8px !important;
  }
}

/* 透明玻璃弹窗样式 */
:deep(.el-dialog) {
  background: rgba(255, 255, 255, 0.02) !important;
  border: 1px solid rgba(255, 255, 255, 0.08) !important;
  backdrop-filter: blur(20px) saturate(150%) !important;
  border-radius: 16px !important;
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;

  .el-dialog__header {
    background: transparent !important;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1) !important;
    padding: 20px 24px 16px 24px !important;

    .el-dialog__title {
      color: #ffffff !important;
      font-size: 18px !important;
      font-weight: 600 !important;
      text-shadow: 0 0 10px rgba(255, 255, 255, 0.3) !important;
    }

    .el-dialog__headerbtn {
      .el-dialog__close {
        color: rgba(255, 255, 255, 0.7) !important;
        font-size: 18px !important;

        &:hover {
          color: #ff4757 !important;
        }
      }
    }
  }

  .el-dialog__body {
    background: transparent !important;
    padding: 24px !important;
    color: #ffffff !important;
  }

  .el-dialog__footer {
    background: transparent !important;
    border-top: 1px solid rgba(255, 255, 255, 0.1) !important;
    padding: 16px 24px 20px 24px !important;
  }
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  color: rgba(255, 255, 255, 0.9) !important;
  font-weight: 500 !important;
}

:deep(.el-input) {
  .el-input__wrapper {
    background: rgba(255, 255, 255, 0.05) !important;
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
    backdrop-filter: blur(10px) !important;
    border-radius: 8px !important;
    box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1) !important;

    &:hover {
      border-color: rgba(0, 234, 255, 0.3) !important;
    }

    &.is-focus {
      border-color: rgba(0, 234, 255, 0.6) !important;
      box-shadow: 0 0 0 2px rgba(0, 234, 255, 0.2) !important;
    }

    .el-input__inner {
      color: #ffffff !important;
      background: transparent !important;

      &::placeholder {
        color: rgba(255, 255, 255, 0.5) !important;
      }
    }
  }
}

:deep(.el-select) {
  .el-select__wrapper {
    background: rgba(255, 255, 255, 0.05) !important;
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
    backdrop-filter: blur(10px) !important;
    border-radius: 8px !important;

    &:hover {
      border-color: rgba(0, 234, 255, 0.3) !important;
    }

    &.is-focused {
      border-color: rgba(0, 234, 255, 0.6) !important;
      box-shadow: 0 0 0 2px rgba(0, 234, 255, 0.2) !important;
    }

    .el-select__selected-item {
      color: #ffffff !important;
    }

    .el-select__placeholder {
      color: rgba(255, 255, 255, 0.5) !important;
    }
  }
}
</style>
